package com.ks.user.controller;

import cn.hutool.http.HttpUtil;
import com.ks.core.base._ControllerBase;
import com.ks.core.constant.Const;
import com.ks.core.core.Result;
import com.ks.core.util.DateUtil;
import com.ks.core.util.JsonUtil;
import com.ks.core.util.ToolUtil;
import com.ks.user.controller.dto.WeChat;
import com.ks.user.controller.dto.WxAuthorRequest;
import com.ks.user.entity.BaseSysConfig;
import com.ks.user.entity.MicroApp;
import com.ks.user.service.IBaseSysConfigService;
import com.ks.user.service.IMicroAppService;
import com.ks.user.service.IWxAuthorService;
import com.ks.user.util.WechatUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kingdee
 * @date 2020/12/22 19:02
 */
@RestController
@RequestMapping("/wx")
@Log
public class WxAuthor extends _ControllerBase {

    @Autowired
    private IWxAuthorService wxAuthorService;
    @Autowired
    private IBaseSysConfigService baseSysConfigService;
    @Autowired
    private IMicroAppService microAppService;

    @PostMapping("/saveTicket")
    @ApiOperation(value = "获取微信后台推送的ticket", notes = "获取微信后台推送的ticket")
    public Object saveTicket(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String msgSignature = request.getParameter("msg_signature");// 微信加密签名
        String timeStamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce"); // 随机数
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuffer sb = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb = sb.append(line);
        }
        String postData = sb.toString();
        try {
            log.info(msgSignature);
            log.info(timeStamp);
            log.info(nonce);
            log.info(postData);
            wxAuthorService.parsePequest(timeStamp, nonce, msgSignature, postData);
        } catch (Exception e) {
            log.info("系统异常");
        } finally {
            // 响应消息
            return "success";
        }
    }


    @PostMapping("/getUserInfo")
    @ApiOperation(value = "获取用户信息手机号",notes = "获取用户信息手机号")
    public Object getUserInfo(@RequestBody WxAuthorRequest request){
        String s = WechatUtils.wxDecrypt(request.getEncrypted(), request.getSession_key(), request.getIv());
        return Result.success(s);
    }

    @GetMapping("/getUserOpenId")
    @ApiOperation(value = "获取用户的openId", notes = "获取用户的openId")
    public Object getUserOpenId(@RequestParam String appId,@RequestParam String secret,@RequestParam String code) {
        String user = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code");
        Map<Object, Object> objectMap = JsonUtil.jsonStrToMap(user);
        return Result.success(objectMap);
    }

    @GetMapping("/getOpenId")
    @ApiOperation(value = "获取用户的openId", notes = "获取用户的openId")
    public Object getOpenId(@RequestParam String appId,@RequestParam String code) {
        String user = HttpUtil.get("https://api.weixin.qq.com/sns/component/jscode2session?appid=" + appId + "&js_code=" + code + "&grant_type=authorization_code&component_appid="+baseSysConfigService.getComponentAppId()+"&component_access_token="+baseSysConfigService.getComponentAccessToken());
        Map<Object, Object> objectMap = JsonUtil.jsonStrToMap(user);
        return Result.success(objectMap);
    }

    @PostMapping("/getComponentAccessToken")
    @ApiOperation(value = "获取第三方平台令牌", notes = "获取第三方平台令牌")
    public Object getComponentAccessToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("component_appid", baseSysConfigService.getComponentAppId());
        map.put("component_appsecret", baseSysConfigService.getComponentAppSecret());
        map.put("component_verify_ticket", baseSysConfigService.getComponentTicket());
        String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/component/api_component_token", JsonUtil.mapToJsonStr(map));
        Map<Object, Object> objectObjectMap = JsonUtil.jsonStrToMap(post);
        if (ToolUtil.isNotEmpty(objectObjectMap.get("component_access_token"))) {
            BaseSysConfig baseSysConfig = baseSysConfigService.selectById(Const.Wx.COMPONENT_TOKEN);
            baseSysConfig.setConfigValue(objectObjectMap.get("component_access_token").toString());
            baseSysConfigService.updateById(baseSysConfig);
            BaseSysConfig config = baseSysConfigService.selectById(6);
            config.setConfigValue(objectObjectMap.get("expires_in").toString());
            baseSysConfigService.updateById(config);
            BaseSysConfig sysConfig = baseSysConfigService.selectById(3);
            sysConfig.setConfigValue(DateUtil.getTimess(DateUtil.getAfterMinuteDate(new Date(), 7200 / 60)));
            baseSysConfigService.updateById(sysConfig);
        }
        return Result.success(post);
    }


    @PostMapping("/getPreAuthCode")
    @ApiOperation(value = "获取预授权码", notes = "获取预授权码")
    public Object getPreAuthCode() {
        Map<String, Object> map = new HashMap<>();
        map.put("component_appid", baseSysConfigService.getComponentAppId());
        String component_access_token = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" + baseSysConfigService.getComponentAccessToken(), JsonUtil.mapToJsonStr(map));
        return component_access_token;
    }

    @GetMapping("/getAuthCode")
    @ApiOperation(value = "获取小程序授权码", notes = "获取小程序授权码")
    public Object getAuthCode(@RequestParam String auth_code, @RequestParam int time, @RequestParam int tenantId) {
        MicroApp microApp = microAppService.getMicroApp(auth_code, time, tenantId);
        return Result.success(microApp);
    }

    @GetMapping("/update")
    @ApiOperation(value = "获取小程序授权码", notes = "获取小程序授权码")
    public void updateAuthCode(@RequestParam String appId,@RequestParam String authorizer_refresh_token) {
        microAppService.updateMicroApp(appId, authorizer_refresh_token);
    }

   /* @PostMapping("/getCommit")
    @ApiOperation(value = "上传代码", notes = "上传代码")
    public Object getCommit(@RequestBody WeChat weChat) {
        int commit = wxAuthorService.Commit(weChat.getTemplate_id(), weChat.getExt_json(), weChat.getUser_version(), weChat.getUser_desc());
        return Result.success(commit);
    }*/

    @PostMapping("/getQrCode")
    @ApiOperation(value = "获取小程序体验版二维码", notes = "获取小程序体验版二维码")
    public Object getQrCode() {
        String qrCode = wxAuthorService.getQrCode(getContext());
        return Result.success(qrCode);
    }

    @PostMapping("/SubmitAudit")
    @ApiOperation(value = "小程序代码提交审核", notes = "小程序代码提交审核")
    public Object SubmitAudit(@RequestBody WeChat weChat) {
        String s = wxAuthorService.SubmitAudit(weChat.getAppId());
        return Result.success(s);
    }

    @PostMapping("/getLatestAuditStatus")
    @ApiOperation(value = "查询最新一次提交的审核状态", notes = "查询最新一次提交的审核状态")
    public Object getLatestAuditStatus(@RequestBody WeChat weChat) {
        Map<String, Object> latestAuditStatus = wxAuthorService.getLatestAuditStatus(weChat.getAppId());
        return Result.success(latestAuditStatus);
    }


    @PostMapping("/getBindQrCode")
    @ApiOperation(value = "获取第三方平台绑定二维码", notes = "获取第三方平台绑定二维码")
    public Object getBindQrCode() {
        getComponentAccessToken();
        Object preAuthCode = getPreAuthCode();
        Map<Object, Object> objectObjectMap = JsonUtil.jsonStrToMap(preAuthCode.toString());
        Object o = objectObjectMap.get("pre_auth_code");
        String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" + baseSysConfigService.getComponentAppId() + "&pre_auth_code=" + objectObjectMap.get("pre_auth_code") + "&redirect_uri=http%3a%2f%2fkstenant.huoyunjishi.cn%2fsettings%2fauthorize%2fauthorizeScs&auth_type=2";
        return Result.success(url);
    }


    @PostMapping("/getApiQueryAuth")
    @ApiOperation(value = "使用授权码获取授权信息", notes = "使用授权码获取授权信息")
    public Object getApiQueryAuth() {
        Map<String, Object> map = new HashMap<>();
        map.put("component_appid", baseSysConfigService.getComponentAppId());
        map.put("authorization_code", "queryauthcode@@@km7AW7g8dPsDS-N06TWWwiEYk3xEwq7sT5ykVUMla-z-YjIG0tMq6iksJqQZfomCYiXGRQkBC_UHRhwL5sxsbw");
        String component_access_token = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + baseSysConfigService.getComponentAccessToken(), JsonUtil.mapToJsonStr(map));
        return component_access_token;
    }


    @PostMapping("/getAuthorizerAccessToken")
    @ApiOperation(value = "获取接口调用令牌", notes = "获取接口调用令牌")
    public Object getAccessToken() {
        Map<String, Object> map = new HashMap<>();
        Map<Object, Object> objectObjectMap1 = JsonUtil.jsonStrToMap(getApiQueryAuth().toString());
        Object authorization_info = objectObjectMap1.get("authorization_info");
        Map<Object, Object> objectObjectMap2 = JsonUtil.jsonStrToMap(authorization_info.toString());
        map.put("component_appid", "wx953429039cd808b1");
        map.put("authorizer_appid", "wx46436cbb5a9f15e5");
        map.put("authorizer_refresh_token", objectObjectMap2.get("authorizer_refresh_token"));
        String component_access_token = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=" + baseSysConfigService.getComponentAccessToken(), JsonUtil.mapToJsonStr(map));
        return component_access_token;
    }

}
